package com.ray.ba.security.app.service.impl;

import com.ray.ba.security.app.service.SecUserService;
import com.ray.ba.security.infra.entity.SecUser;
import com.ray.ba.starter.base.service.BaseServiceImpl;
import com.ray.ba.starter.web.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * SecUserServiceImpl
 *
 * @author ray
 * @date 2020/4/12
 */
@Service
public class SecUserServiceImpl extends BaseServiceImpl<SecUser> implements SecUserService {

    private static final String DEFAULT_PASSWORD = "123456";

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SecUser insert(SecUser entity) {
        List<SecUser> secUserDoList = this.findBy(SecUser.builder().username(entity.getUsername()).build());
        if (!ObjectUtils.isEmpty(secUserDoList)) {
            throw new BaseException(String.format("username:[%s] already exist!", entity.getUsername()));
        }

        secUserDoList = this.findBy(SecUser.builder().email(entity.getEmail()).build());
        if (!ObjectUtils.isEmpty(secUserDoList)) {
            throw new BaseException(String.format("email:[%s] already exist!", entity.getUsername()));
        }

        entity.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD));
        super.insert(entity);
        return entity;
    }

    @Override
    public SecUser update(SecUser entity) {
        SecUser userById = this.findById(entity.getId());
        Assert.notNull(userById, "can not find user by id:" + userById.getId());

        SecUser userByName = this.findOne(SecUser.builder().username(entity.getUsername()).build());
        if (userByName != null && !userById.getId().equals(userByName.getId())) {
            throw new BaseException("username[" + entity.getUsername() + "] is already existed!");
        }

        SecUser userByEmail = this.findOne(SecUser.builder().email(entity.getEmail()).build());
        if (userByEmail != null && !userById.getId().equals(userByEmail.getId())) {
            throw new BaseException("email[" + entity.getEmail() + "] is already existed!");
        }

        return super.update(entity);
    }
}

